﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;

using Newtonsoft.Json;
using SH.STD.Model;
using Cmn;
using SH.STD.DataProvider;
using System.Web.SessionState;


namespace SH.STD.Web.Handler
{
    /// <summary>
    /// Summary description for ProjectAttachment
    /// </summary>
    public class Attachment : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Cache.SetNoStore();
            context.Response.ContentType = "application/json;charset=gb2312";

            switch (context.Request.Params["action"])
            {
                case "loadData":
                    context.Response.Write(ConvertToJsonString());
                    break;
                case "removeData":
                    context.Response.Write(RemoveData(context.Request.Params["jsonDataString"]));
                    break;
                case "addData":
                    context.Response.Write(AddData(context.Request.Params["jsonDataString"]));
                    break;
            }
        }

        private string ConvertToJsonString()
        {
            var tableID = HttpContext.Current.Request.Params["TableID"].ToString().ToInt32();
            var ID = HttpContext.Current.Request.Params["ID"].ToString().ToInt32();
            var sql = @"
SELECT * 
FROM [Attachment] 
WHERE TableID=@TableID and ID=@ID";
            var cmdParams = new SqlParameter[]
                {
                    new SqlParameter("TableID",tableID),
                    new SqlParameter("ID",ID),
                };
            var dt = Cmn.DB.getDataTable(sql, cmdParams);

            return DataAccess.ConvertToJSON(dt, "Attachments");
        }

        private string RemoveData(string jsonDataString)
        {
            JavaScriptObject data = (JavaScriptObject)JavaScriptConvert.DeserializeObject(jsonDataString);
            var tableID = RepsonseInfo.Decode(data["TableID"].ToString()).ToInt32();
            var ID = RepsonseInfo.Decode(data["ID"].ToString()).ToInt32();
            var fileName = RepsonseInfo.Decode(data["FileName"].ToString());

            var delSql = "delete from Attachment where TableID=@TableID and ID=@ID and FileName=@FileName";
            var cmdParams = new SqlParameter[] 
                {
                    new SqlParameter("TableID",tableID),
                    new SqlParameter("ID",ID),
                    new SqlParameter("FileName",fileName)
                };
            Cmn.DB.execSql(delSql, cmdParams);

            return JavaScriptConvert.SerializeObject(new RepsonseInfo { MSG = ID.ToString() });
        }

        private string AddData(string jsonDataString)
        {
            var tableID = HttpContext.Current.Request.Params["TableID"].ToString().ToInt32();
            var ID = HttpContext.Current.Request.Params["ID"].ToString().ToInt32();
            var fileType = RepsonseInfo.Decode(HttpContext.Current.Request.Params["FileType"].ToString());
            fileType = fileType == String.Empty ? "其他" : fileType;
            var lastModifiedBy = Cmn.Session.GetUserID();

            HttpPostedFile f = HttpContext.Current.Request.Files[0];
            var fileName = Path.GetFileName(f.FileName);
            var saveDir = HttpContext.Current.Server.MapPath("~/Upload/" + tableID + @"/" + ID);
            if (!Directory.Exists(saveDir))
            {
                Directory.CreateDirectory(saveDir);
            }
            var filePath = Path.Combine(saveDir, fileName);
            f.SaveAs(filePath);

            var delSql = "delete from Attachment where TableID=@TableID and ID=@ID and FileName=@FileName";
            var cmdParams = new SqlParameter[] 
                {
                    new SqlParameter("TableID",tableID),
                    new SqlParameter("ID",ID),
                    new SqlParameter("FileName",fileName)
                };
            Cmn.DB.execSql(delSql, cmdParams);
            var insertSql = "insert into Attachment (TableID,ID,FileType,FileName,FilePath,LastModifiedBy) values (@TableID,@ID,@FileType,@FileName,@FilePath,@LastModifiedBy)";
            cmdParams = new SqlParameter[] 
                {
                    new SqlParameter("TableID",tableID),
                    new SqlParameter("ID",ID),
                    new SqlParameter("FileType",fileType),
                    new SqlParameter("FileName",fileName),
                    new SqlParameter("FilePath",filePath),
                    new SqlParameter("LastModifiedBy",lastModifiedBy),
                };
            Cmn.DB.execSql(insertSql, cmdParams);

            return JavaScriptConvert.SerializeObject(new RepsonseInfo { MSG = ID.ToString() });
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}